package platform

import (
	"fmt"
	"io"

	"gitee.com/bjf-fhe/apicat/notify"
	"gitee.com/bjf-fhe/apicat/source"
	"github.com/sirupsen/logrus"
	"github.com/spf13/pflag"
)

type Notifier interface{}
type Source interface{}
type Handler interface {
	Check() error
	AddFlags(*pflag.FlagSet)
	GetNotifier(ncfg *notify.Config) (Notifier, error)
	GetSource(fileHandler RootConfiger, tailMode bool) (source.Reader, error)
}
type RootConfiger interface {
	IsLocalFile() bool
	GetFileName() string
	OpenFile() (io.ReadCloser, error)
	GetTimeFormat() string
}

type loadedHandler struct {
	Handler Handler
	inited  bool
}

var handlers = make(map[string]*loadedHandler)

func Register(name string, handler Handler) {
	handlers[name] = &loadedHandler{
		Handler: handler,
	}
}

func GetNotifier(name string, ncfg *notify.Config) (Notifier, error) {
	handler, ok := handlers[name]
	if ok {
		if !handler.inited {
			err := handler.Handler.Check()
			if err != nil {
				return nil, err
			}
			handler.inited = true
		}
		return handler.Handler.GetNotifier(ncfg)
	}
	var names []string
	for k, _ := range handlers {
		names = append(names, k)
	}

	logrus.Errorf("指定的Notify终端%s不存在\n已注册的类型包括：%v\n将采用默认处理", name, names)
	return handlers["print"], nil
}

func GetSource(name string, fileHandler RootConfiger, tailMode bool) (source.Reader, error) {
	handler, ok := handlers[name]
	if ok {
		if !handler.inited {
			err := handler.Handler.Check()
			if err != nil {
				return nil, err
			}
			handler.inited = true
		}
		return handler.Handler.GetSource(fileHandler, tailMode)
	}
	var names []string
	for k, _ := range handlers {
		names = append(names, k)
	}

	return nil, fmt.Errorf("指定的Notify终端%s不存在\n已注册的类型包括：%v\n将采用默认处理", name, names)
}

func AddFlags(set *pflag.FlagSet) {
	for k, v := range handlers {
		var sub = pflag.NewFlagSet(k, pflag.ContinueOnError)
		v.Handler.AddFlags(sub)
		sub.SetNormalizeFunc(func(f *pflag.FlagSet, name string) pflag.NormalizedName {
			return pflag.NormalizedName(k + "-" + name)
		})
		set.AddFlagSet(sub)
	}
}
